package com.weijianhuawen.wjblog.admin.event.subscriber;

import com.weijianhuawen.wjblog.admin.event.UpdateCommentEvent;
import com.weijianhuawen.wjblog.common.domain.dos.BlogSettingsDo;
import com.weijianhuawen.wjblog.common.domain.dos.CommentDo;
import com.weijianhuawen.wjblog.common.domain.mapper.BlogSettingsMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.CommentMapper;
import com.weijianhuawen.wjblog.common.enums.CommentStatusEnum;
import com.weijianhuawen.wjblog.common.exception.BizException;
import com.weijianhuawen.wjblog.common.mail.MailHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-12-22 16:44
 */

@Slf4j
@Component
public class UpdateCommentSubscriber implements ApplicationListener<UpdateCommentEvent> {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private BlogSettingsMapper blogSettingsMapper;
    @Resource
    private MailHelper mailHelper;
    @Value("${blog.base.url}")
    private String baseUrl;
    @Value("${blog.base.path}")
    private String basePath;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(UpdateCommentEvent event) {
        // 获取评论id
        Long commentId = event.getCommentId();

        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("【更新/审核评论事件订阅者】 处理任务线程名：{}", threadName);
        log.info("【更新/审核事件订阅者】 开始消费事件！, 评论id：{}", commentId);

        // 获取评论
        CommentDo commentDo = commentMapper.selectById(commentId);
        Long replyCommentId = commentDo.getReplyCommentId();
        String nickname = commentDo.getNickname();
        String content = commentDo.getContent();
        Integer status = commentDo.getStatus();
        String mail = commentDo.getMail();
        if (mail == null || !MailHelper.validateEmail(mail)) {
            log.info("【更新/审核事件订阅者】 邮箱：{}，格式不正确或为空！", mail);
            return;
        }
        String routerUrl = commentDo.getRouterUrl();

        // 获取博客设置
        BlogSettingsDo blogSettingsDo = blogSettingsMapper.selectById(1L);
        String blogName = blogSettingsDo.getBlogName();
        // 博客域名
        String domain = "http://" + baseUrl + basePath;
        // 判断评论状态
        if (Objects.equals(status, CommentStatusEnum.EXAMINE_FAILED.getCode())) {
            // 评论审核不通过，获取不通过理由
            String reason = commentDo.getReason();
            String title = String.format("你在【%s】的评论审核不通过", blogName);
            // 构建html
            String html = String.format("<html><body>" +
                    "<h2>你的评论:</h2><p>%s，未通过博主审核！</p>" +
                    "<h2>未通过原因：</h2><p>%s</p>"  +
                    "<p><a href='%s%s' target='_blank'>查看详情</a></p>" +
                    "</body></html>", content, reason, domain, routerUrl);

            // 发送邮件
            mailHelper.sendHtml(mail, title, html);
        } else if (Objects.equals(status, CommentStatusEnum.NORMAL.getCode())) {
            // 审核通过
            String title = String.format("你在【%s】的评论已审核通过！", blogName);
            String html = String.format("<html><body>" +
                    "<h2>你的评论:</h2><p>%s，已通过博主审核！</p>" +
                    "<p><a href='%s%s' target='_blank'>查看详情</a></p>" +
                    "</body></html>", content, domain, routerUrl);

            // 发送邮件
            mailHelper.sendHtml(mail, title, html);
            // 通知被回复人，评论已被回复
            notifyBeCommentedUser(replyCommentId, blogName, nickname, content, domain);
        }
    }

    // 通知被回复人评论已回复
    private void notifyBeCommentedUser(Long replyCommentId, String blogName, String nickname, String content, String domain) {
        // 判断回复人评论id是否为空
        if (Objects.isNull(replyCommentId)) return;

        // 被回复评论
        CommentDo replyCommentDo = commentMapper.selectById(replyCommentId);

        // 邮件地址
        String to = replyCommentDo.getMail();
        // 判断邮箱格式
        if (to == null || MailHelper.validateEmail(to)) {
            log.info("【更新/审核事件订阅者】 邮箱：{}，格式不正确或为空！", to);
            return;
        }

        // 回复路由
        String routerUrl = replyCommentDo.getRouterUrl();
        String subject = String.format("【未见花闻博客平台】 您在%s的评论收到了回复", blogName);

        // 构建Html
        String html = String.format("<html><body>" +
                "<h2>你的评论:</h2><p>%s，收到了回复</p>" +
                "<h2>%s 回复了你:</h2><p>%s</p>"  +
                "<p><a href='%s%s' target='_blank'>查看详情</a></p>" +
                "</body></html>", replyCommentDo.getContent(), nickname, content, domain, routerUrl);

        // 发送邮件
        mailHelper.sendHtml(to, subject, html);
    }
}
